package com.example.propertymanagement.service;

import com.example.propertymanagement.dto.OwnerDTO;
import com.example.propertymanagement.dto.VehicleDTO;
import com.example.propertymanagement.entity.Owner;
import com.example.propertymanagement.entity.Vehicle;
import com.example.propertymanagement.repository.VehicleRepository;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * VehicleService：车辆信息的业务逻辑处理层
 */
@Service
public class VehicleService {

    @Autowired
    private VehicleRepository vehicleRepository;

    /**
     * 获取所有车辆信息
     * @return List<VehicleDTO> 车辆信息列表
     */
    public List<VehicleDTO> getAllVehicles() {
        List<Vehicle> vehicles = vehicleRepository.findAll();
        return vehicles.stream().map(this::convertToDTO).collect(Collectors.toList());
    }

    /**
     * 根据车主ID获取车辆信息
     * @param ownerId 车主ID
     * @return List<VehicleDTO> 车辆信息列表
     */
    public List<VehicleDTO> getVehiclesByOwnerId(Integer ownerId) {
        List<Vehicle> vehicles = vehicleRepository.findByOwnerId(ownerId);
        return vehicles.stream().map(this::convertToDTO).collect(Collectors.toList());
    }

    /**
     * 根据车牌号查找车辆
     * @param plateNumber 车牌号
     * @return VehicleDTO 车辆信息
     */
    public VehicleDTO getVehicleByPlateNumber(String plateNumber) {
        Vehicle vehicle = vehicleRepository.findByPlateNumber(plateNumber);
        return vehicle != null ? convertToDTO(vehicle) : null;
    }

    /**
     * 将 Vehicle 实体转换为 VehicleDTO
     * @param vehicle 车辆实体
     * @return VehicleDTO 数据传输对象
     */
    private VehicleDTO convertToDTO(Vehicle vehicle) {
        VehicleDTO dto = new VehicleDTO();
        dto.setId(vehicle.getId());
        dto.setVehiclePhoto(vehicle.getVehiclePhoto());
        dto.setColor(vehicle.getColor());
        dto.setPlateNumber(vehicle.getPlateNumber());
        dto.setRemark(vehicle.getRemark());
        dto.setCreateTime(vehicle.getCreateTime());

        // 转换 Owner 实体为 OwnerDTO
        OwnerDTO ownerDTO = convertOwnerToDTO(vehicle.getOwner());
        dto.setOwner(ownerDTO);

        return dto;
    }

    /**
     * 将 Owner 实体转换为 OwnerDTO
     * @param owner 业主实体
     * @return OwnerDTO 业主数据传输对象
     */
    private OwnerDTO convertOwnerToDTO(Owner owner) {
        if (owner == null) {
            return null;
        }
        OwnerDTO ownerDTO = new OwnerDTO();
        ownerDTO.setId(owner.getId());
        ownerDTO.setMemberName(owner.getMemberName());
        ownerDTO.setContactPhone(owner.getContactPhone());
        ownerDTO.setGender(owner.getGender());
        ownerDTO.setMemberType(owner.getMemberType());
        ownerDTO.setCommunityName(owner.getCommunity() != null ? owner.getCommunity().getCommunityName() : null);
        ownerDTO.setPropertyName(owner.getProperty() != null ? owner.getProperty().getPropertyName() : null);
        ownerDTO.setRemark(owner.getRemark());
        return ownerDTO;
    }

    /**
     * 将 VehicleDTO 转换为 Vehicle 实体
     * @param vehicleDTO 车辆数据传输对象
     * @return Vehicle 实体对象
     */
    public Vehicle convertToEntity(VehicleDTO vehicleDTO) {
        Vehicle vehicle = new Vehicle();
        vehicle.setId(vehicleDTO.getId());
        vehicle.setVehiclePhoto(vehicleDTO.getVehiclePhoto());
        vehicle.setColor(vehicleDTO.getColor());
        vehicle.setPlateNumber(vehicleDTO.getPlateNumber());
        vehicle.setRemark(vehicleDTO.getRemark());
        vehicle.setCreateTime(vehicleDTO.getCreateTime());

        // 将 OwnerDTO 转换为 Owner 实体并设置到 Vehicle 中
        Owner owner = convertOwnerDTOToEntity(vehicleDTO.getOwner());
        vehicle.setOwner(owner);

        return vehicle;
    }

    /**
     * 将 OwnerDTO 转换为 Owner 实体
     * @param ownerDTO 业主数据传输对象
     * @return Owner 业主实体
     */
    private Owner convertOwnerDTOToEntity(OwnerDTO ownerDTO) {
        if (ownerDTO == null) {
            return null;
        }
        Owner owner = new Owner();
        owner.setId(ownerDTO.getId());
        owner.setMemberName(ownerDTO.getMemberName());
        owner.setContactPhone(ownerDTO.getContactPhone());
        owner.setGender(ownerDTO.getGender());
        owner.setMemberType(ownerDTO.getMemberType());
        // 如果有社区和房产的关联，可以在这里根据需要设置
        return owner;
    }

    // === 以下是添加、删除、更新的业务逻辑 === //

    /**
     * 添加车辆信息
     * @param vehicleDTO 车辆数据传输对象
     * @return VehicleDTO 新添加的车辆信息
     */
    @Transactional
    public VehicleDTO addVehicle(VehicleDTO vehicleDTO) {
        // 将 VehicleDTO 转换为 Vehicle 实体
        Vehicle vehicle = convertToEntity(vehicleDTO);
        // 保存车辆信息到数据库
        Vehicle savedVehicle = vehicleRepository.save(vehicle);
        // 返回保存后的车辆信息（转换为 DTO）
        return convertToDTO(savedVehicle);
    }

    /**
     * 更新车辆信息
     * @param vehicleDTO 车辆数据传输对象
     * @return VehicleDTO 更新后的车辆信息
     */
    @Transactional
    public VehicleDTO updateVehicle(VehicleDTO vehicleDTO) {
        // 根据 ID 查找车辆
        Optional<Vehicle> existingVehicleOptional = vehicleRepository.findById(vehicleDTO.getId());
        if (existingVehicleOptional.isPresent()) {
            Vehicle existingVehicle = existingVehicleOptional.get();
            // 更新车辆信息
            existingVehicle.setVehiclePhoto(vehicleDTO.getVehiclePhoto());
            existingVehicle.setColor(vehicleDTO.getColor());
            existingVehicle.setPlateNumber(vehicleDTO.getPlateNumber());
            existingVehicle.setRemark(vehicleDTO.getRemark());
            existingVehicle.setCreateTime(vehicleDTO.getCreateTime());

            // 更新 Owner 信息
            Owner owner = convertOwnerDTOToEntity(vehicleDTO.getOwner());
            existingVehicle.setOwner(owner);

            // 保存更新后的车辆信息
            Vehicle updatedVehicle = vehicleRepository.save(existingVehicle);

            return convertToDTO(updatedVehicle);
        } else {
            return null; // 如果车辆不存在，返回 null
        }
    }

    /**
     * 删除车辆信息
     * @param vehicleId 车辆ID
     */
    @Transactional
    public void deleteVehicle(Integer vehicleId) {
        // 根据 ID 查找车辆
        Optional<Vehicle> existingVehicleOptional = vehicleRepository.findById(vehicleId);
        if (existingVehicleOptional.isPresent()) {
            // 删除车辆记录
            vehicleRepository.delete(existingVehicleOptional.get());
        } else {
            throw new RuntimeException("Vehicle not found with ID: " + vehicleId);
        }
    }
}